package com.burt.zookeeper.curator;

import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.zookeeper.CreateMode;

/**
 * Description: User: Burt
 * Date: 2017-08-08 Time: 23:40
 */
public class CuratorEventDemo {
    /**
     * 三种watcher来做节点的监听
     * pathcache   监视一个路径下子节点的创建、删除、节点数据更新
     * NodeCache   监视一个节点的创建、更新、删除
     * TreeCache   pathcaceh+nodecache 的合体（监视路径下的创建、更新、删除事件），
     * 缓存路径下的所有子节点的数据
     */

    public static void main(String[] args) throws Exception {
        CuratorFramework curatorFramework = CuratorClientUtils.getInstance();

        /**
         * 节点变化NodeCache
         */
//        final NodeCache nodeCache = new NodeCache(curatorFramework,"/curator",false);
//        nodeCache.start(true);
//
//        nodeCache.getListenable().addListener(()-> System.out.println("节点数据发生变化，变化后的结果 :"
//                + new String(nodeCache.getCurrentData().getData())));
//
//        curatorFramework.setData().forPath("/curator","Burt".getBytes());

        /**
         * pathcache
         */
        PathChildrenCache childrenCache = new PathChildrenCache(curatorFramework,"/event",true);
        childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        // Normal  初始化为空
        // BUILD_INITIAL_CACHE 在方法返回之前调用rebuild的操作
        // POST_INITIALIZED_EVENT cache初始化之后发送一个ChildrenCacheEvent的事件

        childrenCache.getListenable().addListener((curatorFramework1, pathChildrenCacheEvent)->{
            switch (pathChildrenCacheEvent.getType()){
                case CHILD_ADDED:
                    System.out.println("添加子节点");
                    break;
                case CHILD_REMOVED:
                    System.out.println("删除子节点");
                    break;
                case CHILD_UPDATED:
                    System.out.println("更新子节点");
                    break;
                    default:break;
            }
        });

        curatorFramework.create().withMode(CreateMode.PERSISTENT).forPath("/event","event".getBytes());
        TimeUnit.SECONDS.sleep(1);

        curatorFramework.create().withMode(CreateMode.PERSISTENT).forPath("/event/event1","1".getBytes());
        TimeUnit.SECONDS.sleep(1);

        curatorFramework.setData().forPath("/event/event1","666".getBytes());
        TimeUnit.SECONDS.sleep(1);

        curatorFramework.delete().forPath("/event/event1");

        System.in.read();
    }
}
